<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>个人简介</title>
    <link rel="shortcut icon" href="/public/favicon.ico" type="image/x-icon">
    <!-- 引入 Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- 引入 Font Awesome -->
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <!-- 引入 Bootstrap -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

    <!-- 配置 Tailwind -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        secondary: '#36D399',
                        neutral: {
                            100: '#F8FAFC',
                            200: '#E2E8F0',
                            300: '#CBD5E1',
                            400: '#94A3B8',
                            500: '#64748B',
                            600: '#475569',
                            700: '#334155',
                            800: '#1E293B',
                            900: '#0F172A',
                        }
                    },
                    fontFamily: {
                        inter: ['Inter', 'system-ui', 'sans-serif'],
                    },
                    boxShadow: {
                        'card': '0 10px 15px -3px rgba(0, 0, 0, 0.05), 0 4px 6px -2px rgba(0, 0, 0, 0.03)',
                        'card-hover': '0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04)',
                    }
                },
            }
        }
    </script>

    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .text-balance {
                text-wrap: balance;
            }
            .animate-fade-in {
                animation: fadeIn 0.5s ease-in-out;
            }
            .animate-slide-up {
                animation: slideUp 0.5s ease-out;
            }
            .scrollbar-hide {
                -ms-overflow-style: none;
                scrollbar-width: none;
            }
            .scrollbar-hide::-webkit-scrollbar {
                display: none;
            }
        }

        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }

        @keyframes slideUp {
            from { transform: translateY(20px); opacity: 0; }
            to { transform: translateY(0); opacity: 1; }
        }
    </style>
    <style>
        .profile-image {
            width: 150px;
            height: 150px;
            object-fit: cover;
            border-radius: 50%;
            border: 3px solid #fff;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }
        .image-upload {
            position: relative;
            display: inline-block;
        }
        .image-upload input[type="file"] {
            display: none;
        }
        .image-upload label {
            cursor: pointer;
            position: absolute;
            bottom: 0;
            right: 0;
            background: #fff;
            padding: 5px 10px;
            border-radius: 20px;
            box-shadow: 0 0 5px rgba(0,0,0,0.2);
        }
    </style>
</head>
<body class="font-inter bg-neutral-100 text-neutral-800">
<!-- 导航栏 -->
<header class="sticky top-0 z-50 bg-white shadow-sm transition-all duration-300" id="navbar">
    <div class="container mx-auto px-4 py-3 flex items-center justify-between">
        <div class="flex items-center space-x-2">
            <a href="/qian/home.html" class="text-primary font-bold text-xl flex items-center">
                <i class="fa fa-graduation-cap mr-2"></i>
                <span>StudentHub</span>
            </a>
        </div>

        <nav class="hidden md:flex items-center space-x-6">
            <a href="/qian/home.html" class="text-primary font-medium">首页</a>
            <!-- 后台管理按钮 -->
            <a href="/hou/index.html" id="adminButton" class="hidden bg-primary text-white px-3 py-1 rounded font-medium hover:bg-primary/90 transition-colors">
                后台管理
            </a>
        </nav>

        <div class="flex items-center space-x-4">
            <!-- Logout Button -->
            <button id="logoutButton" class="text-red-500 hover:text-red-700 transition-colors font-medium hidden md:block">
                退出登录
            </button>

            <div class="relative hidden md:block">
                <label>
                    <input type="text" placeholder="搜索课程、学习资料..." class="pl-10 pr-4 py-2 rounded-full bg-neutral-100 focus:outline-none focus:ring-2 focus:ring-primary/30 transition-all w-48 focus:w-64">
                </label>
                <i class="fa fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-neutral-400"></i>
            </div>

            <div class="relative group">
                <a href="/qian/user-center.html" class="w-4 h-4 rounded-full overflow-hidden border-2 border-white hover:border-primary transition-all">
                    <!-- Server-side code should replace the src with the user's avatar from session -->
                    <img src="https://picsum.photos/id/64/200/200" alt="用户头像" class="w-full h-full object-cover rounded-full" style="width: 40px; height: 40px;">
                </a>

                <div class="absolute right-0 mt-2 w-48 bg-white rounded-lg shadow-lg py-2 z-10 opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-300 transform group-hover:translate-y-0 translate-y-2">
                    <a href="user.html" class="block px-4 py-2 text-sm text-neutral-700 hover:bg-neutral-100">
                        <i class="fa fa-user-o mr-2"></i> 个人主页
                    </a>
                    <a href="#" class="block px-4 py-2 text-sm text-neutral-700 hover:bg-neutral-100">
                        <i class="fa fa-cog mr-2"></i> 设置
                    </a>
                    <div class="border-t border-neutral-200 my-1"></div>
                </div>
            </div>

            <button class="md:hidden text-neutral-600 hover:text-primary transition-colors">
                <i class="fa fa-bars text-xl"></i>
            </button>
        </div>
    </div>
</header>

<!-- 主内容区 -->
<main class="container py-5">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2 class="mb-0">个人简介</h2>
    </div>

    <div class="card">
        <div class="card-body">
            <form id="profileForm">
                <div class="text-center mb-4">
                    <div class="image-upload">
                        <img src="https://picsum.photos/id/1005/150/150" alt="个人头像" class="profile-image" id="profileImage">
                        <label for="imageInput">
                            <i class="fa fa-camera"></i>
                        </label>
                        <input type="file" id="imageInput" accept="image/*">
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label for="nickName" class="form-label">昵称</label>
                        <input type="text" class="form-control" id="nickName" required>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label for="email" class="form-label">电子邮箱</label>
                        <input type="email" class="form-control" id="email" required>
                    </div>
                </div>

                <div class="mb-3">
                    <label class="form-label">性别</label>
                    <div class="d-flex gap-3">
                        <div class="form-check">
                            <input class="form-check-input" type="radio" name="gender" id="male" value="男">
                            <label class="form-check-label" for="male">男</label>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input" type="radio" name="gender" id="female" value="女">
                            <label class="form-check-label" for="female">女</label>
                        </div>
                    </div>
                </div>

                <div class="mb-3">
                    <label for="bio" class="form-label">个人简介</label>
                    <textarea class="form-control" id="bio" rows="4" maxlength="500"></textarea>
                    <div class="form-text text-end">
                        <span id="charCount">0</span>/500
                    </div>
                </div>

                <button type="submit" class="btn btn-primary">保存修改</button>
            </form>
        </div>
    </div>
</main>

<!-- 底部区域 -->
<footer class="bg-white border-t border-neutral-200 mt-12">
    <div class="container mx-auto px-4 py-8">
        <div class="grid grid-cols-1 md:grid-cols-4 gap-8">
            <div>
                <h3 class="text-lg font-bold text-neutral-900 mb-4">StudentHub</h3>
                <p class="text-neutral-600 text-sm mb-4">探索知识，提升能力，与优秀学子共同成长。</p>
                <div class="flex space-x-4">
                    <a href="#" class="text-neutral-500 hover:text-primary transition-colors">
                        <i class="fa fa-github text-xl"></i>
                    </a>
                    <a href="#" class="text-neutral-500 hover:text-primary transition-colors">
                        <i class="fa fa-twitter text-xl"></i>
                    </a>
                    <a href="#" class="text-neutral-500 hover:text-primary transition-colors">
                        <i class="fa fa-linkedin text-xl"></i>
                    </a>
                    <a href="#" class="text-neutral-500 hover:text-primary transition-colors">
                        <i class="fa fa-weibo text-xl"></i>
                    </a>
                </div>
            </div>
        </div>

        <div class="border-t border-neutral-200 mt-8 pt-8 text-center text-neutral-500 text-sm">
            
        </div>
    </div>
</footer>

<script src="/jquery-3.7.1.min.js"></script>
<script>
    $(document).ready(function() {
        // Dynamically set the header avatar from sessionStorage
        const userAvatarName = sessionStorage.getItem('avatarUrl'); // Get the avatar filename from sessionStorage using the key 'avatarUrl'
        const headerAvatar = $('#navbar a.rounded-full img'); // Corrected selector for the avatar image in the header
        const avatarBaseUrl = 'http://localhost:8082/upload/';
        if (userAvatarName && headerAvatar.length > 0) {
            headerAvatar.attr('src', avatarBaseUrl + userAvatarName);
        } else {
            // Optionally set a default avatar if not found in session
            headerAvatar.attr('src', 'http://localhost:8082/upload/default.jpg');
        }

        // Control visibility of Admin button based on user role
        const userRole = sessionStorage.getItem('userRole'); // Assuming user role is stored under this key
        const adminButton = $('#adminButton');

        if (userRole === 'ADMIN') {
            adminButton.removeClass('hidden');
        } else {
            adminButton.addClass('hidden');
        }

        // 获取当前用户ID
        const userId = sessionStorage.getItem('userId'); // 从sessionStorage获取用户ID

        if (!userId) {
            alert('用户未登录或登录信息已过期，请重新登录。');
            window.location.href = 'login.html'; // 跳转到登录页面
            return;
        }

        // 加载个人资料
        function loadProfile() {
            $.ajax({
                url: `http://localhost:8082/api/user/profile/${userId}`,
                method: 'GET',
                success: function(response) {
                    if (response.code === 200) {
                        const data = response.data;
                        console.log(data);
                        
                        // 设置表单值，如果值为null则设置为空字符串
                        $('#nickName').val(data.nickName || '');
                        $('#email').val(data.email || '');
                        // 处理性别选择
                        if (data.gender) {
                            console.log('Gender value:', data.gender);
                            $(`input[name="gender"][value="${data.gender}"]`).prop('checked', true);
                        }
                        $('#bio').val(data.bio || '');
                        if (data.avatarUrl) {
                            $('#profileImage').attr('src', 'http://localhost:8082/upload/' + data.avatarUrl);
                        } else {
                            // 如果没有头像，使用默认头像
                            $('#profileImage').attr('src', 'https://picsum.photos/id/1005/150/150');
                        }
                        updateCharCount();
                    }
                },
                error: function(xhr, status, error) {
                    alert('获取个人资料失败：' + error);
                }
            });
        }

        // 更新字数统计
        function updateCharCount() {
            const count = $('#bio').val().length;
            $('#charCount').text(count);
        }

        // 监听简介输入
        $('#bio').on('input', updateCharCount);

        // 处理头像上传
        $('#imageInput').on('change', function(e) {
            const file = e.target.files[0];
            if (file) {
                // 创建 FormData 对象
                const formData = new FormData();
                formData.append('file', file);

                // 上传文件
                $.ajax({
                    url: 'http://localhost:8082/api/upload/img',
                    method: 'POST',
                    data: formData,
                    processData: false,  // 不处理数据
                    contentType: false,  // 不设置内容类型
                    success: function(response) {
                        if (response.code === 200) {
                            // 上传成功，更新头像显示
                            const avatarUrl = 'http://localhost:8082/upload/' + response.data;
                            $('#profileImage').attr('src', avatarUrl);
                            // 保存头像文件名到表单数据中
                            $('#profileForm').data('avatarUrl', response.data);
                            // 更新sessionStorage中的头像文件名
                            sessionStorage.setItem('avatarUrl', response.data);
                            alert('头像上传成功！');
                        } else {
                            alert('头像上传失败：' + response.msg);
                        }
                    },
                    error: function(xhr, status, error) {
                        alert('头像上传失败：' + error);
                    }
                });
            }
        });

        // 处理表单提交
        $('#profileForm').on('submit', function(e) {
            e.preventDefault();
            
            const formData = {
                userId: userId,
                nickName: $('#nickName').val(),
                email: $('#email').val(),
                gender: $('input[name="gender"]:checked').val(),
                bio: $('#bio').val(),
                avatarUrl: $('#profileForm').data('avatarUrl') || null
            };

            $.ajax({
                url: 'http://localhost:8082/api/user/profile/',
                method: 'PUT',
                contentType: 'application/json',
                data: JSON.stringify(formData),
                success: function(response) {
                    if (response.code === 200) {
                        alert('个人资料更新成功');
                    } else {
                        alert('更新失败：' + response.msg);
                    }
                },
                error: function(xhr, status, error) {
                    alert('更新失败：' + error);
                }
            });
        });

        // 初始加载个人资料
        loadProfile();

        // Add logout functionality for the button
        $('#logoutButton').on('click', function(e) {
            e.preventDefault(); // Prevent default link behavior
            // Clear session storage
            sessionStorage.removeItem('userId');
            sessionStorage.removeItem('username'); // Assuming username is also stored
            sessionStorage.removeItem('avatarUrl');
            sessionStorage.removeItem('userRole'); // Assuming userRole is also stored

            // Redirect to login page
            window.location.href = '/login.html'; // Replace with your login page path
        });
    });
</script>
</body>

<!-- 底部区域
<footer class="bg-white border-t border-neutral-200 mt-12">
    <div class="container mx-auto px-4 py-8">
        <div class="grid grid-cols-1 md:grid-cols-4 gap-8">
            <div>
                <h3 class="text-lg font-bold text-neutral-900 mb-4">StudentHub</h3>
                <p class="text-neutral-600 text-sm mb-4">探索知识，提升能力，与优秀学子共同成长。</p>
                <div class="flex space-x-4">
                    <a href="#" class="text-neutral-500 hover:text-primary transition-colors">
                        <i class="fa fa-github text-xl"></i>
                    </a>
                    <a href="#" class="text-neutral-500 hover:text-primary transition-colors">
                        <i class="fa fa-twitter text-xl"></i>
                    </a>
                    <a href="#" class="text-neutral-500 hover:text-primary transition-colors">
                        <i class="fa fa-linkedin text-xl"></i>
                    </a>
                    <a href="#" class="text-neutral-500 hover:text-primary transition-colors">
                        <i class="fa fa-weibo text-xl"></i>
                    </a>
                </div>
            </div>
        </div>

        <div class="border-t border-neutral-200 mt-8 pt-8 text-center text-neutral-500 text-sm">
            
        </div>
    </div>
</footer> -->

</html> 